package com.ruoyi.labdata.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.labdata.domain.LabDeclarationFiling;
import com.ruoyi.labdata.domain.LabFlowInstance;
import com.ruoyi.labdata.service.ILabFlowInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.labdata.mapper.LabOrgnizationMapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.labdata.domain.LabOrgnization;
import com.ruoyi.labdata.service.ILabOrgnizationService;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 机构Service业务层处理
 * 
 * @author winner pan
 * @date 2022-02-02
 */
@Service
public class LabOrgnizationServiceImpl implements ILabOrgnizationService {
	@Autowired
	private LabOrgnizationMapper labOrgnizationMapper;
	@Autowired
	private ISysDeptService deptService;

	@Autowired
	private ILabFlowInstanceService labFlowInstanceService;

	/**
	 * 查询机构
	 * 
	 * @param orgId
	 *            机构ID
	 * @return 机构
	 */
	@Override
	public LabOrgnization selectLabOrgnizationById(Long orgId) {
		return labOrgnizationMapper.selectLabOrgnizationById(orgId);
	}

	/**
	 * 查询机构列表
	 * 
	 * @param labOrgnization
	 *            机构
	 * @return 机构
	 */
	@Override
	public List<LabOrgnization> selectLabOrgnizationList(LabOrgnization labOrgnization) {
		return labOrgnizationMapper.selectLabOrgnizationList(labOrgnization);
	}

	/**
	 * 新增机构
	 * 
	 * @param labOrgnization
	 *            机构
	 * @return 结果
	 */
	@Override
	@Transactional
	public int insertLabOrgnization(LabOrgnization labOrgnization) {
		if(labOrgnization.getOrgStatusOpt()==null){
			labOrgnization.setOrgStatusOpt(Long.valueOf(0));
		}
		int orgID = labOrgnizationMapper.insertLabOrgnization(labOrgnization);

		SysDept dept = new SysDept();
		dept.setCreateTime(new Date());
		dept.setDelFlag("0");
		dept.setDeptId(labOrgnization.getOrgId());
		dept.setDeptName(labOrgnization.getOrgName());
		dept.setParentId(labOrgnization.getParentId());
		dept.setStatus(labOrgnization.getOrgStatusOpt().toString());
		dept.setCreateBy(labOrgnization.getCreateBy());
		dept.setOrderNum(labOrgnization.getOrderNum());
		if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
			throw new RuntimeException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
		}
		deptService.insertDept(dept);
		return orgID;
	}

	/**
	 * 修改机构
	 * 
	 * @param labOrgnization
	 *            机构
	 * @return 结果
	 */
	@Override
	@Transactional
	public int updateLabOrgnization(LabOrgnization labOrgnization) {
		// 判断流程是否走完
		if (null != labOrgnization.getInstanceId()){
			LabFlowInstance labFlowInstance = new LabFlowInstance();
			labFlowInstance.setInstanceId(labOrgnization.getInstanceId());
			labFlowInstance.setFlowStatusOpt("committed");
			List<LabFlowInstance> labFlowInstances = labFlowInstanceService.selectLabFlowInstanceList(labFlowInstance);
			if (CollUtil.isNotEmpty(labFlowInstances) && labFlowInstances.size() >0){
				throw new RuntimeException("不能进行修改,提交的申报备案的流程未走完!");
			}
		}

		SysDept sysDept = new SysDept();
		sysDept.setDeptId(labOrgnization.getOrgId());
		sysDept.setDeptName(labOrgnization.getOrgName());
		sysDept.setParentId(labOrgnization.getParentId());
		sysDept.setStatus(labOrgnization.getOrgStatusOpt() + "");
		deptService.updateDept(sysDept);
		labOrgnizationMapper.updateLabOrgnizationInstanceIdNull(labOrgnization.getOrgId());
		return labOrgnizationMapper.updateLabOrgnization(labOrgnization);
	}

	/**
	 * 批量删除机构
	 * 
	 * @param orgIds
	 *            需要删除的机构ID
	 * @return 结果
	 */
	@Override
	public int deleteLabOrgnizationByIds(Long[] orgIds) {
		return labOrgnizationMapper.deleteLabOrgnizationByIds(orgIds);
	}

	/**
	 * 删除机构信息
	 * 
	 * @param orgId
	 *            机构ID
	 * @return 结果
	 */
	@Override
	public int deleteLabOrgnizationById(Long orgId) {
		return labOrgnizationMapper.deleteLabOrgnizationById(orgId);
	}

	@Override
	public List<LabOrgnization> queryLabOrgnizationByName(String orgName) {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		return labOrgnizationMapper.queryUserThirdLabByName(orgName, user.getDeptId());
	}

	public List<LabOrgnization> getOrgByFunctionOpt(Long orgFunctionOpt) {
		return labOrgnizationMapper.getOrgByFunctionOpt(orgFunctionOpt);
	}

	public List<LabOrgnization> listLabBySecondOrgId(Long orgId) {
		return labOrgnizationMapper.listLabBySecondOrgId(orgId);
	}

	@Override
	public List<Tree> buildOrgnizationTreeSelect(List<LabOrgnization> labOrgnizations) {
		List<LabOrgnization> deptTrees = buildDeptTree(labOrgnizations);
		return deptTrees.stream().map(Tree::new).collect(Collectors.toList());
	}

	/**
	 * 构建前端所需要树结构
	 *
	 * @param labOrgnizations
	 *            部门列表
	 * @return 树结构列表
	 */
	public List<LabOrgnization> buildDeptTree(List<LabOrgnization> labOrgnizations) {
		List<LabOrgnization> returnList = new ArrayList<LabOrgnization>();
		List<Long> tempList = new ArrayList<Long>();
		for (LabOrgnization labOrgnization : labOrgnizations) {
			tempList.add(labOrgnization.getOrgId());
		}
		for (Iterator<LabOrgnization> iterator = labOrgnizations.iterator(); iterator.hasNext();) {
			LabOrgnization labOrgnization = (LabOrgnization) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(labOrgnization.getParentId())) {
				recursionFn(labOrgnizations, labOrgnization);
				returnList.add(labOrgnization);
			}
		}
		if (returnList.isEmpty()) {
			returnList = labOrgnizations;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 */
	private void recursionFn(List<LabOrgnization> list, LabOrgnization t) {
		// 得到子节点列表
		List<LabOrgnization> childList = getChildList(list, t);
		t.setChildren(childList);
		for (LabOrgnization tChild : childList) {
			if (hasChild(list, tChild)) {
				recursionFn(list, tChild);
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<LabOrgnization> getChildList(List<LabOrgnization> list, LabOrgnization t) {
		List<LabOrgnization> tlist = new ArrayList<LabOrgnization>();
		Iterator<LabOrgnization> it = list.iterator();
		while (it.hasNext()) {
			LabOrgnization n = (LabOrgnization) it.next();
			if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getOrgId().longValue()) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<LabOrgnization> list, LabOrgnization t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}
	
	public Integer checkOrgUsed(Long orgId){
		return this.labOrgnizationMapper.checkOrgUsed(orgId);
	}

	@Override
	public List<LabOrgnization> chooseOrgsQuery(LabOrgnization labOrgnization) {
		return labOrgnizationMapper.chooseOrgsQuery(labOrgnization);
	}
	
	public List<LabOrgnization> getLabOrgnizationTreeList(LabOrgnization labOrgnization){
		return labOrgnizationMapper.getLabOrgnizationTreeList(labOrgnization);
	}
	
	public List<LabOrgnization> listPlatformOrgTree(){
		List<LabOrgnization> labOrgnizationList = labOrgnizationMapper.listPlatformOrgTree();
		Map<Long,LabOrgnization> platformMap = new HashMap<Long, LabOrgnization>();
		//
		LabOrgnization root = new LabOrgnization();
		root.setOrgName("国家、省级实验平台");
		root.setOrgId(Long.valueOf(0));
		platformMap.put(root.getOrgId(), root);
		for(LabOrgnization orgnization : labOrgnizationList){
			if(platformMap.get(orgnization.getOrgGroupOpt())==null){
				LabOrgnization platformOrgnization = new LabOrgnization();
				platformOrgnization.setOrgId(orgnization.getOrgGroupOpt());
				platformOrgnization.setOrgName(orgnization.getParentName());
				platformOrgnization.setParentId(Long.valueOf(0));
				platformMap.put(orgnization.getOrgGroupOpt(), platformOrgnization);
			}
		}
		labOrgnizationList.addAll(platformMap.values());
		return labOrgnizationList;
	}

	@Override
	public int updateLabOrgnizationInstanceId(LabDeclarationFiling labDeclarationFiling) {
		return labOrgnizationMapper.updateLabOrgnizationInstanceId(labDeclarationFiling);
	}

	@Override
	public int updateLabOrgnizationInstanceIdNull(Long  orgId) {
		return labOrgnizationMapper.updateLabOrgnizationInstanceIdNull(orgId);
	}

	@Override
	public List<LabOrgnization> listLabByOrgId(Long orgId) {
		return labOrgnizationMapper.listLabByOrgId(orgId);
	}

}
